package com.gdit.zax.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gdit.zax.dao.FindPwdDao;
import com.gdit.zax.dao.UserDao;
import com.gdit.zax.entitys.FindPwd;
import com.gdit.zax.entitys.UserInfo;
import com.gdit.zax.factory.DAOFactory;
import com.gdit.zax.utils.DBUtil;
import com.gdit.zax.utils.MD5;
import com.gdit.zax.utils.O;
import com.gdit.zax.utils.TextUtil;
import com.gdit.zax.utils.VeriFicUtil;

public class ChangePwd extends HttpServlet {
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String username = request.getParameter("username");
		String changeflag = request.getParameter("changeflag");
		String newpwd = MD5.getMD5(request.getParameter("newpwd"));
		
		//检测参数
		if (TextUtil.isEmpty(username)) {
			O.printFail(response, 1, "请检查usernam参数!");
			return;
		}
		if (TextUtil.isEmpty(changeflag)) {
			O.printFail(response, 1, "请检查changeflag参数!");
			return;
		}
		if (TextUtil.isEmpty(newpwd)) {
			O.printFail(response, 1, "请检查newpwd参数!");
			return;
		}
		
		//检测连接、用户
		Connection conn = DBUtil.getConnection();
		if (conn==null) {
			O.printFail(response, 1000, "数据库连接失败!");
			return;
		}
		
		//开始
		DAOFactory dao = DAOFactory.init(conn, request, response);
		FindPwdDao fdao = dao.getFindPwdDao();
		
		FindPwd finfo =fdao.getFindPwd(changeflag);
		if (finfo==null) {
			O.printFail(response, 1, "无效的密码修改标记，请重新验证密码!");
			return;
		}
		if (!fdao.changePwd(finfo.getUserid(), changeflag, newpwd)){
			O.printFail(response, 1, "修改失败，请经过验证码验证!");
			return;
		}
		
		UserDao udao = dao.getUserDao();
		UserInfo uinfo = udao.getInfo(finfo.getUserid());
		
		Map<String, Object> map =new HashMap<String, Object>();
		map.put("userid", uinfo.getId());
		map.put("accesstoken", VeriFicUtil.getIDVF(uinfo.getId()));
		
		O.printSuccess(response, map);
	}

}
